package com.unlcn.ils.wms.web.controller.outbound;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.domain.ResultDTOWithPagination;
import cn.huiyunche.commons.exception.BusinessException;
import com.alibaba.fastjson.JSON;
import com.unlcn.ils.wms.backend.bo.outboundBO.WmsPreparationPlanBO;
import com.unlcn.ils.wms.backend.enums.WarehouseEnum;
import com.unlcn.ils.wms.backend.service.outbound.WmsPreparationPlanService;
import com.unlcn.ils.wms.backend.util.BrowerEncodeingUtils;
import com.unlcn.ils.wms.base.dto.WmsPreparationPlanDTO;
import com.unlcn.ils.wms.base.dto.WmsPreparationPlanResultDTO;
import com.unlcn.ils.wms.web.utils.Vo2Bo;
import com.unlcn.ils.wms.web.vo.outbound.WmsPreparationPlanVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 出库备料计划
 * Created by DELL on 2017/9/26.
 */
@Controller
@RequestMapping("/wmsPreparationPlan")
@ResponseBody
public class WmsPreparationPlanController {

    private Logger logger = LoggerFactory.getLogger(WmsPreparationPlanController.class);

    @Autowired
    WmsPreparationPlanService wmsPreparationPlanService;

    /**
     * 备料计划管理查询
     * <p>2017-12-28 新需求:加上实际入场时间，实际出场时间，支持数据导出</p>
     *
     * @param jsonStr 参数对象
     * @param request 请求
     * @return 返回值
     * @throws Exception 异常
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ResultDTO list(@RequestBody String jsonStr, HttpServletRequest request) throws Exception {
        logger.info("WmsPreparationPlanController.list jsonStr: {}", jsonStr);
        if (jsonStr == null) {
            throw new Exception("参数为null");
        }
        ResultDTO<Object> resultDTO = new ResultDTO<>();
        try {
            Map<String, Object> paramMap = JSON.parseObject(jsonStr);
            resultDTO.setSuccess(true);
            resultDTO.setMessage("查询备料计划成功");

            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                return resultDTO;
            }
            paramMap.put("ppWhCode", whCode);
            String userId = request.getHeader("userId");
            if (StringUtils.isNotBlank(userId)) {
                paramMap.put("opStaff", userId);
            }
            resultDTO.setData(wmsPreparationPlanService.list(paramMap));
            return resultDTO;
        } catch (Exception ex) {
            logger.error("WmsPreparationPlanController.list error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询备料计划异常");
            return resultDTO;
        }
    }

    /**
     * 获取备料明细详情
     *
     * @param ppId
     * @return
     */
    @RequestMapping("/getVehicleDetail/{ppId}")
    public ResultDTO<Object> getVehicleDetail(@PathVariable("ppId") String ppId) {
        logger.info("WmsPreparationPlanController.getVehicleDetail ppId: {}", ppId);
        ResultDTO<Object> resultDTO = new ResultDTO<>();
        try {
            resultDTO.setSuccess(true);
            resultDTO.setMessage("查询备料计划详情成功");
            resultDTO.setData(wmsPreparationPlanService.getVehicleDetail(ppId));
            return resultDTO;
        } catch (Exception ex) {
            logger.error("WmsPreparationPlanController.getVehicleDetail error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("查询备料计划详情异常");
            return resultDTO;
        }
    }

    /**
     * 创建备料任务
     * <p>
     * 2018-4-20 bugfix 修复重复任务出现
     * </p>
     *
     * @param wmsPreparationPlanVOList 参数封装
     * @return 返回值
     */
    @RequestMapping(value = "/createPlan/{estimateLaneId}", method = RequestMethod.POST)
    public ResultDTO<Object> createPlan(@PathVariable("estimateLaneId") Long estimateLaneId,
                                        @RequestBody List<WmsPreparationPlanVO> wmsPreparationPlanVOList,
                                        HttpServletRequest request) {
        logger.info("WmsPreparationPlanController.createPlan estimateLaneId: {}", estimateLaneId);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "操作成功");
        String whCode = request.getHeader("whCode");
        if (StringUtils.isBlank(whCode)) {
            resultDTO.setSuccess(false);
            resultDTO.setMessage("当前登录用户未绑定仓库");
            return resultDTO;
        }
        try {
            Vo2Bo vo2Bo = new Vo2Bo();
            List<WmsPreparationPlanBO> wmsPreparationPlanBOList = vo2Bo.convert(wmsPreparationPlanVOList, WmsPreparationPlanBO.class);
            if (WarehouseEnum.UNLCN_XN_CQ.getWhCode().equals(whCode)) {
                wmsPreparationPlanService.savePreparationTaskForCqNew(estimateLaneId, wmsPreparationPlanBOList, whCode);
            } else if (WarehouseEnum.JM_XY.getWhCode().equals(whCode) || WarehouseEnum.JM_CS.getWhCode().equals(whCode)) {
                wmsPreparationPlanService.savePreparationTask(estimateLaneId, wmsPreparationPlanBOList, whCode);
            }
            resultDTO.setSuccess(true);
            resultDTO.setMessage("生成备料任务成功");
        } catch (BusinessException e) {
            logger.error("WmsPreparationPlanController.createPlan BusinessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
            throw new BusinessException(e.getMessage());
        } catch (Exception ex) {
            logger.error("WmsPreparationPlanController.createPlan error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("生成备料任务异常");
            throw new BusinessException("生成备料任务异常");
        }
        return resultDTO;
    }

    /**
     * 发运变更 - 增车
     *
     * @param ppId
     */
    @RequestMapping(value = "/updateShipToAddPlan/{ppId}", method = RequestMethod.POST)
    public ResultDTO<Object> updateShipToAddPlan(@PathVariable("ppId") Long ppId) {
        logger.info("WmsPreparationPlanController.updateShipToAddPlan ppId: {}", ppId);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "增车成功");
        try {
            //发运变更 - 增车
            wmsPreparationPlanService.updateShipToPreparePlan(ppId);
        } catch (BusinessException e) {
            logger.error("WmsPreparationPlanController.updateShipToAddPlan businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("WmsPreparationPlanController.updateShipToAddPlan error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("增车失败");
        }
        return resultDTO;
    }

    /**
     * 发运变更 - 剔除
     *
     * @param vdId
     * @return
     */
    @RequestMapping(value = "/deletePreparetionDetail/{vdId}", method = RequestMethod.POST)
    public ResultDTO<Object> deletePreparetionDetail(@PathVariable("vdId") Long vdId) {
        logger.info("WmsPreparationPlanController.deletePreparetionDetail vdId: {}", vdId);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "剔除成功");
        try {
            //发运变更 - 剔除
            wmsPreparationPlanService.deletePreparetionDetail(vdId);
        } catch (BusinessException e) {
            logger.error("WmsPreparationPlanController.deletePreparetionDetail businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("WmsPreparationPlanController.deletePreparetionDetail error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("剔除失败");
        }
        return resultDTO;
    }

    /**
     * 发运变更 - 任务
     *
     * @param ppId
     * @return
     */
    @RequestMapping(value = "/updateShipmentToTask/{ppId}", method = RequestMethod.POST)
    public ResultDTO<Object> updateShipmentToTask(@PathVariable("ppId") Long ppId, HttpServletRequest request) {
        logger.info("WmsPreparationPlanController.updateShipmentToTask ppId: {}", ppId);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "发运变更成功");
        try {
            //发运变更 - 变更任务
            String whCode = request.getHeader("whCode");
            if (StringUtils.isBlank(whCode)) {
                resultDTO.setSuccess(false);
                resultDTO.setMessage("当前登录用户未绑定仓库");
                return resultDTO;
            }
            wmsPreparationPlanService.updateShipmentToTask(ppId, whCode);
        } catch (BusinessException e) {
            logger.error("WmsPreparationPlanController.updateShipmentToTask businessException: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(e.getMessage());
        } catch (Exception e) {
            logger.error("WmsPreparationPlanController.updateShipmentToTask error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("发运变更失败");
        }
        return resultDTO;
    }

    /**
     * 手动创建备料计划页面的列表查询
     * 2017/12/25 新需求:西南库股份业务 中转业务需要能手动创建备料计划
     *
     * @param dto     参数封装对象
     * @param request 请求
     * @return 返回值
     * @throws Exception 异常
     */
    @RequestMapping(value = "/getStockTransferList", method = RequestMethod.POST)
    public ResultDTOWithPagination<Object> getStockTransferList(@RequestBody WmsPreparationPlanDTO dto, HttpServletRequest request) throws Exception {
        logger.info("WmsPreparationPlanController.getStockTransferList param: {}", dto);
        ResultDTOWithPagination<Object> resultDTO = new ResultDTOWithPagination<>(true, null, "查询成功!");
        try {
            String whCode = request.getHeader("whCode");
            String userId = request.getHeader("userId");
            dto.setWhCode(whCode);
            dto.setUserId(userId);
            ResultDTOWithPagination<List<WmsPreparationPlanResultDTO>> data = wmsPreparationPlanService.getStockTransferList(dto);
            resultDTO.setData(data.getData());
            resultDTO.setPageVo(data.getPageVo());
        } catch (BusinessException ex) {
            logger.error("WmsPreparationPlanController.getStockTransferList error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(ex.getMessage());
        } catch (Exception e) {
            logger.error("WmsPreparationPlanController.getStockTransferList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("系统异常");
        }
        return resultDTO;
    }

    /**
     * 手动创建备料计划
     * 2017/12/25 新需求:西南库股份业务 中转业务需要能手动创建备料计划
     *
     * @param dto     参数封装对象
     * @param request 请求
     * @return 返回值
     * @throws Exception 异常
     */
    @RequestMapping(value = "/savePreparationPlanStockTransfer", method = RequestMethod.POST)
    public ResultDTO<Object> savePreparationPlanStockTransfer(@RequestBody WmsPreparationPlanDTO dto, HttpServletRequest request) throws Exception {
        logger.info("WmsPreparationPlanController.savePreparationPlanStockTransfer param: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "操作成功!");
        try {
            String whCode = request.getHeader("whCode");
            String userId = request.getHeader("userId");
            dto.setWhCode(whCode);
            dto.setUserId(userId);
            wmsPreparationPlanService.savePreparationPlanStockTransfer(dto);
        } catch (BusinessException ex) {
            logger.error("WmsPreparationPlanController.savePreparationPlanStockTransfer error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(ex.getMessage());
        } catch (Exception e) {
            logger.error("WmsPreparationPlanController.savePreparationPlanStockTransfer error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("系统异常");
        }
        return resultDTO;
    }

    /**
     * 动态获取客户名称下拉框接口
     * 2017/12/25 新需求:西南库股份业务 中转业务需要能手动创建备料计划
     *
     * @param request 请求
     * @return 返回值
     * @throws Exception 异常
     */
    @RequestMapping(value = "/getCustomerNameList", method = RequestMethod.GET)
    public ResultDTO<Object> getCustomerNameList(HttpServletRequest request) throws Exception {
        logger.info("WmsPreparationPlanController.getCustomerNameList param: {}");
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功!");
        try {
            String whCode = request.getHeader("whCode");
            String userId = request.getHeader("userId");
            WmsPreparationPlanDTO dto = new WmsPreparationPlanDTO();
            dto.setWhCode(whCode);
            dto.setUserId(userId);
            resultDTO.setData(wmsPreparationPlanService.getCustomerNameList(dto));
        } catch (BusinessException ex) {
            logger.error("WmsPreparationPlanController.getCustomerNameList error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(ex.getMessage());
        } catch (Exception e) {
            logger.error("WmsPreparationPlanController.getCustomerNameList error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("系统异常");
        }
        return resultDTO;
    }


    /**
     * 备料计划的导出功能
     * <p>2017-12-28 备料计划的数据导出</p>
     *
     * @param request 请求
     * @return 返回值
     * @throws Exception 异常
     */
    @RequestMapping(value = "/getImportExcelData", method = RequestMethod.GET)
    public ResultDTO<Object> getImportExcelData(WmsPreparationPlanDTO dto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("WmsPreparationPlanController.getImportExcelData param: {}", dto);
        ResultDTO<Object> resultDTO = new ResultDTO<>(true, null, "查询成功!");
        BufferedOutputStream bufferedOutputStream = null;
        ServletOutputStream outputStream = null;
        HSSFWorkbook workbook = null;
        try {
            String whCode = request.getHeader("whCode");
            String userId = request.getHeader("userId");
            dto.setWhCode(whCode);
            dto.setUserId(userId);
            workbook = wmsPreparationPlanService.getImportExcelData(dto);
            //输出流--提供下载
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition", BrowerEncodeingUtils.getContentDisposition("preparationImportExcel.xls", request));
            outputStream = response.getOutputStream();
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            workbook.write(bufferedOutputStream);
        } catch (IOException e) {
            logger.error("WmsPreparationPlanController.getImportExcelData paramTracking", e);
        } catch (BusinessException ex) {
            logger.error("WmsPreparationPlanController.getImportExcelData error: {}", ex);
            resultDTO.setSuccess(false);
            resultDTO.setMessage(ex.getMessage());
        } catch (Exception e) {
            logger.error("WmsPreparationPlanController.getImportExcelData error: {}", e);
            resultDTO.setSuccess(false);
            resultDTO.setMessage("系统异常");
        } finally {
            if (bufferedOutputStream != null) {
                bufferedOutputStream.flush();
                bufferedOutputStream.close();
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (workbook != null) {
                workbook.close();
            }
        }
        return resultDTO;
    }

}
